import { Controller } from 'egg';

class UserController extends Controller {
  async login() {
    const { ctx, app } = this;
    const req: {
      userInfo: any
    } = ctx.request.body;
    const data = await ctx.service.user.userLogin(req.userInfo).catch(err => {
      ctx.body = {
        code: 500,
        msg: '服务器出错了',
        error: err,
      };
    });
    if (req.userInfo && req.userInfo.username && req.userInfo.password) {
      ctx.body = {
        ...data,
        token: app.jwt.sign({
          username: data.username, // 需要存储的 token 数据
        }, app.config.jwt.secret),
      };
    } else {
      ctx.body = {
        ...data,
        msg: '参数错误',
      };
    }

  }

  async addUser() {
    const { ctx } = this;
    const req: {
      userInfo: object
    } = ctx.request.body;
    ctx.body = await ctx.service.user.addUser(req.userInfo);
  }

  async updateUser() {
    const { ctx } = this;
    const req: object = ctx.request.body;
    ctx.body = await ctx.service.user.updateUser(req);
  }
  async logout() {
    //  var userinfo=this.ctx.session
    const { ctx } = this;
    const userinfo = ctx.request.body;
    ctx.session = null;
    ctx.body = {
      code: 200,
      msg: '注销成功',
    };
    return ctx.logger.info(userinfo, '注销成功');
  }
}

module.exports = UserController;
